package typ

import (
	"errors"
	"net"
	"strconv"
	"strings"
)

type IPInt uint32

func (ipInt IPInt) String() string {
	return net.IPv4(byte((ipInt>>24)&0xFF), byte((ipInt>>16)&0xFF), byte((ipInt>>8)&0xFF), byte(ipInt&0xFF)).String()
}

type IPStr string

func (ipStr IPStr) String() string {
	return string(ipStr)
}

func (ipStr IPStr) ToIPInt() (IPInt, error) {
	var sum uint32
	bits := strings.Split(ipStr.String(), ".")
	if len(bits) != 4 {
		return IPInt(sum), errors.New("typ format err")
	}
	b0, _ := strconv.Atoi(bits[0])
	b1, _ := strconv.Atoi(bits[1])
	b2, _ := strconv.Atoi(bits[2])
	b3, _ := strconv.Atoi(bits[3])

	sum += uint32(b0) << 24
	sum += uint32(b1) << 16
	sum += uint32(b2) << 8
	sum += uint32(b3)
	return IPInt(sum), nil
}
